#pragma once
#include "index.hpp"
#include <algorithm>
#include <jsoncpp/json/json.h>
namespace Searcher
{
    class searcher
    {
        struct InvertedElemPrint
        {
            uint64_t doc_id;
            int weight;
            std::vector<std::string> words;
            InvertedElemPrint() : doc_id(0), weight(0) {}
        };

    public:
        searcher()
        {
        }
        ~searcher()
        {
        }

        void InitSearcher(const std::string &input)
        {
            // 获取/创建index对象
            _index = Index::index::GetInstance();
            LOG(NORMAL,"获取单例成功");
            // 通过index对象构建索引
            _index->BuildIndex(input);
            LOG(NORMAL,"建立正排和倒排成功");
        }

        void Search(const std::string &_query, std::string *_json_string)
        {
            // 1.对用户传入的搜素关键字进行 分词
            std::vector<std::string> _words;
            Util::JiebaUtil::CutString(_query, &_words);
            std::vector<InvertedElemPrint> _inverted_list_all;
            std::unordered_map<uint64_t, InvertedElemPrint> _token_map;
            // 2.根据分出的各个词进行index查找
            for (auto word : _words)
            {
                boost::to_lower(word);
                auto it = _index->GetInvertIndex(word);
                for (auto &item : *it)
                {
                    auto &Merage = _token_map[item.doc_id];
                    Merage.doc_id = item.doc_id;
                    Merage.weight += item.weight;
                    Merage.words.push_back(item._key_word);
                }
            }

            for (auto item : _token_map)
            {
                _inverted_list_all.push_back(std::move(item.second));
            }

            // 3.汇总查找结果 按照weight的值进行降序排序
            std::sort(_inverted_list_all.begin(), _inverted_list_all.end(),
                      [](const InvertedElemPrint &e1, const InvertedElemPrint &e2) -> bool
                      { return e1.weight > e2.weight; });
            // 4.根据查找结果构建json串 返回给用户 --jsoncpp

            Json::Value root;
            for (auto &item : _inverted_list_all)
            {
                Index::DocInfo *doc = _index->GetForwardIndex(item.doc_id);
                if (nullptr == doc)
                {
                    continue;
                }
                Json::Value elem;
                elem["title"] = doc->_title;
                elem["desc"] = GetDesc(doc->_content, item.words[0]);
                elem["url"] = doc->_url;

                root.append(elem);
            }

            Json::FastWriter writer;
            *_json_string = writer.write(root);
        }

        std::string GetDesc(const std::string &content, const std::string &key_word)
        {
            const int prev_step = 50;
            const int next_step = 100;
            auto iter = std::search(content.begin(), content.end(), key_word.begin(), key_word.end(), [](int x, int y)
                                    { return (std::tolower(x) == std::tolower(y)); });
            if (iter == content.end())
            {
                return "None1";
            }
            int pos = std::distance(content.begin(), iter);
            int end = content.size() - 1;
            int start = 0;

            if (pos < end - next_step)
            {
                end = pos + next_step;
            }

            if (pos > start + prev_step)
            {
                start = pos - prev_step;
            }

            if (start >= end)
            {
                return "None2";
            }
            return content.substr(start, end - start);
        }

    private:
        Index::index *_index; // 用于查找的索引
    };
}